package excel.csv_excel;

import java.io.*;
import java.util.StringTokenizer;

/**
 * 读取和写入csv格式的excel文件csv的数据是通过,隔开的
 */
public class CsvTest {
    public static void readcsv(File file){
        try{
        InputStreamReader isr = new InputStreamReader(new FileInputStream(file), "utf-8");
        BufferedReader br = new BufferedReader(isr);
// 读取直到最后一行
        String line = "";
        while ((line = br.readLine()) != null) {
            // 把一行数据分割成多个字段
            StringTokenizer st = new StringTokenizer(line, ",");
            while (st.hasMoreTokens()) {
                // 每一行的多个字段用TAB隔开表示
                String msg=  new String(st.nextToken().getBytes("utf-8"),"utf-8");
                //System.out.println();
                System.out.print(msg + "\t");
            }
            System.out.println();
        }
        br.close();
    } catch (FileNotFoundException e) {
        // 捕获File对象生成时的异常
        e.printStackTrace();
    } catch (IOException e) {
        // 捕获BufferedReader对象关闭时的异常
        e.printStackTrace();
    }
}
public static void writecsv(File file) throws IOException {//写入的类
        OutputStream outputStream=new FileOutputStream(file,true);

        OutputStreamWriter outputStreamWriter=new OutputStreamWriter(outputStream,"utf-8");

       BufferedWriter bw=new BufferedWriter(outputStreamWriter);

    bw.write("1" + "," + "消息1" + "," + "10");//写入
    bw.newLine();//换行
    bw.write("2" + "," + "消息2" + "," + "20");//写入
    bw.newLine();
    bw.write("3" + "," + "消息3" + "," + "30");//写入
    bw.newLine();
    bw.write("4" + "," + "消息4" + "," + "40");//写入
    bw.newLine();
    System.out.println("写入成功");
    bw.flush();
    bw.close();
}


    public static void main(String[] args) throws IOException{


        File csv=new File("E:\\宏图学习之旅\\poi\\Writers.csv"); // CSV文件
        readcsv(csv);//读取文件
        writecsv(csv);
        readcsv(csv);//读取文件
        }
}
